package com.blackfish.common.plugin;
import java.io.IOException;

import com.blackfish.common.config.Conf;
import com.blackfish.common.plugin.aio.FindUdpHandler;
import com.blackfish.common.plugin.aio.HelloPacket;
import com.blackfish.common.plugin.aio.HelloServerAioHandler;
import com.jfinal.plugin.IPlugin;
import java.io.IOException;

//import org.tio.examples.helloworld.common.Const;
import org.tio.core.udp.UdpServer;
import org.tio.core.udp.UdpServerConf;
import org.tio.server.TioServer;
import org.tio.server.ServerGroupContext;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;


public class TioPlugin implements IPlugin{
    //static ServerAioHandler aioHandler = new HelloServerAioHandler();
//    public static ServerGroupContext serverGroupContext = new ServerGroupContext(aioHandler,null);
//    static AioServer aioServer = new AioServer(serverGroupContext); // 可以为空
//    static ServerAioListener aioListener = null;
//    static String serverIp = null;
//    static int serverPort = Conf.PORT;

    //handler, 包括编码、解码、消息处理
    public static ServerAioHandler aioHandler = new HelloServerAioHandler();

    //事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
    public static ServerAioListener aioListener = null;

    //一组连接共用的上下文对象
    public static ServerGroupContext serverGroupContext = new ServerGroupContext("hello-tio-server", aioHandler, aioListener);

    //tioServer对象
    public static TioServer tioServer = new TioServer(serverGroupContext);

    //有时候需要绑定ip，不需要则null
    public static String serverIp = null;

    //监听的端口
    public static int serverPort = Conf.PORT;



    public static void main(String[] args) throws IOException {
        aioHandler = new HelloServerAioHandler();
        aioListener = null; // 可以为空
        serverGroupContext = new ServerGroupContext(aioHandler, aioListener);
        tioServer = new TioServer(serverGroupContext);
        serverGroupContext.setHeartbeatTimeout(Conf.TIMEOUT);


        tioServer.start(serverIp, serverPort);
    }

    @Override
    public boolean start() {
        aioHandler = new HelloServerAioHandler();
        aioListener = null; // 可以为空
        serverGroupContext = new ServerGroupContext(aioHandler, aioListener);
        tioServer = new TioServer(serverGroupContext);
        try {
            tioServer.start(serverIp, serverPort);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean stop() {
        return tioServer.stop();
    }
}